package com.hulytu.android.push;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.util.ArrayMap;
import android.util.Log;

import com.hulytu.android.ThinDroid;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author Chris (hulytu@163.com)
 * @date 2021/11/12
 */
public class AppPushManager {

    public static final String PLATFORM_DEFAULT = "platform.default";

    private static final String TAG = "AppPushManager";

    protected AppPushManager() {
    }

    public static AppPushManager getInstance() {
        return Holder.MANAGER;
    }

    private static class Holder {
        static final AppPushManager MANAGER = new AppPushManager();
    }

    private final Map<String, AppPush> pushCache = new ArrayMap<>();

    private final List<BroadcastReceiver> receivers = new ArrayList<>();

    private boolean mInit;

    public AppPush getDefault() {
        AppPush push = getPush(PLATFORM_DEFAULT);
        if (push != null) return push;

        if (pushCache.size() == 1) {
            // 只有一个的时候直接返回第一个
            Collection<AppPush> values = pushCache.values();
            Iterator<AppPush> iterator = values.iterator();
            if (iterator.hasNext()) return iterator.next();
        }

        return null;
    }

    public void setDefault(AppPush push) {
        addPush(PLATFORM_DEFAULT, push);
    }

    public void addPush(String platform, AppPush push) {
        AppPush cache = pushCache.get(platform);
        if (cache == null || PLATFORM_DEFAULT.equals(platform)) {
            pushCache.put(platform, push);
        } else if (cache != push) {
            throw new IllegalArgumentException("This platform is already exist! => " + platform);
        }
    }

    public void removePush(String platform) {
        pushCache.remove(platform);
    }

    public AppPush getPush(String platform) {
        return pushCache.get(platform);
    }

    /**
     * 从 AndroidManifest.xml中读取匹配 {@link AppPush#RECEIVER_ACTION} 的广播
     *
     * @param context
     */
    private void init(Context context) {
        if (mInit) return;
        mInit = true;

        Intent intent = new Intent(AppPush.RECEIVER_ACTION);
        intent.setPackage(context.getPackageName());

        PackageManager pm = context.getPackageManager();

        @SuppressLint("QueryPermissionsNeeded")
        List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(intent, 0);

        if (resolveInfos != null && !resolveInfos.isEmpty()) {

            for (ResolveInfo resolveInfo : resolveInfos) {
                try {
                    Class<?> cls = Class.forName(resolveInfo.activityInfo.name);
                    if (BroadcastReceiver.class.isAssignableFrom(cls)) {
                        BroadcastReceiver instance = (BroadcastReceiver) cls.newInstance();
                        receivers.add(instance);
                    }
                } catch (Exception e) {
                    if (ThinDroid.isDebug()) e.printStackTrace();
                }

            } // end for-each

        } // end if

        if (ThinDroid.isDebug() && receivers.isEmpty()) {
            Log.e(TAG, "You must set at least one value. ( " + AppPush.RECEIVER_ACTION + " )");
        }
    }

    /**
     * 数据分发
     *
     * @param context
     * @param intent
     */
    public void publish(@NotNull Context context, Intent intent) {
        if (intent == null) return;

        // 首次进行自动扫描
        if (receivers.isEmpty()) init(context);

        for (BroadcastReceiver receiver : receivers) {
            receiver.onReceive(context, intent);
        }
    }

}
